<template>
  <div class="view-container">
    <header-module :left-custom="true" :padding="true">
      <template #left-con>
        <div>
          <span style="font-size: 16px; margin-right: 20px">
            导入流向数据
          </span>
        </div>
      </template>
      <template #btn>
        <el-button class="border-btn" size="small" style="margin-right: 20px;" @click="handlBack">返回</el-button>
        <el-button class="border-btn" size="small" style="margin-right: 20px;" @click="handlSave">保存草稿</el-button>
        <el-button class="main-btn" size="small" type="primary" @click="handlSubmit">提交审核</el-button>
      </template>
    </header-module>

    <div class="main-content">
      <div class="filter-container">
        <el-form ref="formDataRef" :model="formData" :rules="rules" class="filter-form-inline" label-position="left"
          label-width="100px" size="small">
          <el-form-item label="代理名称" prop="agentName">
            <el-autocomplete v-model="formData.agentName" :fetch-suggestions="querySearchDistributors"
              placeholder="请输入代理名称" style="width: 100%" @select="handleSelectDistributors">
              <template #default="{ item }">
                <div class="distributeName">{{ item.agentName }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item label="导入方式">
            <el-radio-group v-model="formData.createType" @click="handlRadio">
              <el-radio :label="2">Excel导入</el-radio>
              <el-radio :label="1">手工录入</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="formData.radio === 1" label="附件">
            <upload-file-view ref="uploadFileView" />
          </el-form-item>
        </el-form>
      </div>

      <div class="list-container">
        <el-tabs v-model="activeName" :before-leave="handlBefore">
          <el-tab-pane label="原始流向数据" name="1">
            <component :is="isComponent" ref="componentTabs" :boole-table="booleTable" :distribute="distribute"
              :form-data-table="formDataTable" :table-data="tableData" :trading="false" @succsessDate="succsessDate"
              @succsessDeleteIds="succsessDeleteIds" />
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

  </div>
</template>

<script>
import {
  computed,
  defineAsyncComponent,
  getCurrentInstance,
  inject,
  onMounted,
  reactive,
  toRefs,
} from "vue";
import { useRoute, useRouter } from "vue-router";

export default {
  name: "Index",
  components: {
    excelOriginal: defineAsyncComponent(() =>
      import("../modules/excelOriginal.vue")
    ),
    manualOriginal: defineAsyncComponent(() =>
      import("../modules/manualOriginal.vue")
    ),
  },
  setup() {
    const api = inject("api");
    const router = useRouter();
    const route = useRoute();
    var data = reactive({
      formData: {
        agentName: "",
        agentId: 0,
        createType: 1,
        file: [],
      },
      rules: {
        agentName: [
          { required: true, message: "请输入代理商名称", trigger: "change" },
        ],
      },
      activeName: "1",
      tableData: [],
      distribute: {},
      deliveryDirection: [],
      deleteIds: [],
      formDataRef: null,
      formTable: {},
      formDataTable: {},
      booleTable: false,
    });
    const currentInstance = getCurrentInstance();

    // 获取代理商列表
    const querySearchDistributors = async (queryString, cb) => {
      let results = [];
      const res = await api.businessFlow.TBUSINESSFLOW_AGENT(queryString);
      if (res.code === 0) {
        results = res.data.list || [];
      }
      cb(results);
    };

    // 代理商事件
    const handleSelectDistributors = (val) => {
      data.formData.agentName = val?.agentName;
      data.formData.agentId = val?.id;
      data.distribute = {
        agentName: val.agentName,
        agentId: val.id,
      };
    };

    const succsessDate = (val) => {
      data.deliveryDirection = val?.tableList; // [...val, ...data.tableData]
      if (data.deleteIds.length > 0) {
        for (let i = 0; i < data.deleteIds.length; i++) {
          data.deliveryDirection.splice(i, 1);
        }
      }
    };

    const succsessDeleteIds = (val) => {
      data.deleteIds = val;
      data.deliveryDirection = val.tableList;
    };

    const handlBack = () => {
      router.go(-1);
    };

    //计算组件
    const isComponent = computed(() => {
      let isComponent = "";
      if (data.formData.createType === 1) {
        isComponent = "manualOriginal";
      }
      if (data.formData.createType === 2) {
        isComponent = "excelOriginal";
      }
      return isComponent;
    });

    // 保存草稿
    const handlSave = () => {
      handPut()
        .then((a) => {
          currentInstance.proxy.customMessage({
            type: "success",
            message: a.msg,
          });
        })
        .catch((a) => {
          currentInstance.proxy.customMessage({
            type: "error",
            message: a.msg,
          });
        });
    };

    // 提交
    const handlSubmit = () => {
      handPut()
        .then((a) => {
          if (a.id !== 0) {
            api.businessFlow.TBUSINESSFLOW_SUBMIT(a.id).then((res) => {
              if (res.code === 0) {
                currentInstance.proxy.customMessage({
                  type: "success",
                  message: "提交成功",
                });
                handlBack();
              } else {
                currentInstance.proxy.customMessage({
                  type: "error",
                  message: res.msg,
                });
              }
            });
          }
        })
        .catch((a) => {
          currentInstance.proxy.customMessage({
            type: "error",
            message: a.msg,
          });
        });
    };

    // 创建保存
    const handPut = () => {
      return new Promise((resolve, reject) => {
        data.formDataRef.validate((valid) => {
          if (valid) {
            if (data.deliveryDirection.length === 0) {
              currentInstance.proxy.customMessage({
                type: "error",
                message: "至少添加一条数据",
              });
              return;
            }
            const dataForm = {
              businessFlow: {
                agentName: data.formData.agentName,
                agentId: data.formData.agentId,
                businessFlowType: route.query.type,
              },
              deliveryDirection: data.deliveryDirection,
              createType: data.formData.createType,
            };
            const dataForm1 = {
              businessFlow: data.formTable,
              deliveryDirection: data.deliveryDirection,
              createType: data.formData.createType,
            };
            const a = {
              a: 0,
              msg: "",
              id: 0,
            };
            if (
              data.formTable.id === undefined &&
              route.query.id === undefined
            ) {
              api.businessFlow.TBUSINESSFLOW_CRRATED(dataForm).then((res) => {
                if (res.code === 0) {
                  data.formTable = res.data.businessFlow;
                  data.booleTable = true;
                  handlDetail(data.formTable.id);
                  a.a = 1;
                  a.msg = "保存成功";
                  a.id = res.data.businessFlow.id;
                  resolve(a);
                } else {
                  data.booleTable = false;
                  a.a = 2;
                  a.msg = res.msg;
                  a.id = 0;
                  reject(a);
                }
              });
            } else {
              api.businessFlow.TBUSINESSFLOW_EDITOR(dataForm1).then((res) => {
                if (res.code === 0) {
                  handlDetail(res.data.businessFlow.id);
                  data.booleTable = true;
                  a.a = 1;
                  a.msg = "编辑成功";
                  a.id = res.data.businessFlow.id;
                  resolve(a);
                } else {
                  data.booleTable = false;
                  a.a = 2;
                  a.msg = res.msg;
                  a.id = 0;
                  reject(a);
                }
              });
            }
          }
        });
      });
    };

    // 获取详情
    const handlDetail = (id) => {
      api.businessFlow.TBUSINESSFLOW_DETAIL(id).then((res) => {
        if (res.code === 0) {
          data.formDataTable = res.data;
          if (route.query.id) {
            data.formTable = res.data.businessFlow.businessFlow;
          }
          if (data.activeName === "1") {
            handlList(1);
          }
          data.formData.agentName =
            res.data.businessFlow.businessFlow.agentName;
          data.formData.agentId = res.data.businessFlow.businessFlow.agentId;
          data.distribute = {
            agentName: res.data.businessFlow.businessFlow.agentName,
            agentId: res.data.businessFlow.businessFlow.agentId,
          };
        }
      });
    };

    const handlList = (type) => {
      const dataList = {
        id: Number(data.formTable.id) || Number(route.query.id),
        type: type,
      };
      api.businessFlow.TBUSINESSFLOW_DETAIL_LIST(dataList).then((res) => {
        if (res.code === 0) {
          data.tableData = res.data.list;
          if (type === 1) {
            data.deliveryDirection = res.data.list;
          }
        }
      });
    };

    onMounted((_) => {
      if (route.query.id) {
        handlDetail(route.query.id);
        handlList(1);
        data.booleTable = true;
      }
    });

    return {
      ...toRefs(data),
      querySearchDistributors,
      handleSelectDistributors,
      handlSubmit,
      handlBack,
      handlSave,
      handPut,
      handlDetail,
      handlList,
      isComponent,
      succsessDate,
      succsessDeleteIds,
    };
  },
};
</script>

<style scoped>
/* @import url(); 引入css类 */
</style>
